package com.yict.csms.company.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yict.common.entity.PageEntity;
import com.yict.common.service.impl.CommonService;
import com.yict.csms.company.dao.impl.ContractDaoImpl;
import com.yict.csms.company.dao.impl.ContractRateDaoImpl;
import com.yict.csms.company.entity.Contract;
import com.yict.csms.company.entity.ContractRate;
import com.yict.csms.company.service.IContractService;

/**
 * 
 * 
 * @author Patrick.Deng
 * 
 */
@Service
public class ContractServiceImpl extends CommonService<Contract, Long>
		implements IContractService {
	@Autowired
	private ContractDaoImpl contractDao;
	private ContractRateDaoImpl contractRateDao;

	public List<Contract> search(Map<String, Object> queryMap, PageEntity page) {
		StringBuilder queryString = new StringBuilder();
		pageEntity = new PageEntity();
		queryString.append("from Contract as c where 1=1");
		if (queryMap != null && queryMap.size() > 0) {
			if (queryMap.get("companyIdList") != null && !"".equals(queryMap.get("companyIdList"))) {
				queryString.append(" and c.company.companyId in (:companyIdList)");
			}
			if (queryMap.get("companyName") != null && !"".equals(queryMap.get("companyName"))) {
				queryString.append(" and lower(c.company.companyName) like :companyName");
				queryMap.put("companyName", queryMap.get("companyName").toString().toLowerCase());
			}
			if (queryMap.get("contractNo") != null && !"".equals(queryMap.get("contractNo"))) {
				queryString.append(" and lower(c.contractNo) like :contractNo");
				queryMap.put("contractNo", queryMap.get("contractNo").toString().toLowerCase());
			}
			if (queryMap.get("effectiveDate1") != null && !"".equals(queryMap.get("effectiveDate1"))
					&& queryMap.get("effectiveDate2") != null && !"".equals(queryMap.get("effectiveDate2"))) {
				queryString
						.append(" and c.effectiveDate >= to_date(:effectiveDate1,'yyyy-mm-dd') and c.effectiveDate <= to_date(:effectiveDate2,'yyyy-mm-dd')");
			}
			if (queryMap.get("expirationDate1") != null && !"".equals(queryMap.get("expirationDate1"))) {
				queryString.append(" and c.expirationDate >= to_date(:expirationDate1,'yyyy-mm-dd') ");
			}
			if (queryMap.get("expirationDate2") != null && !"".equals(queryMap.get("expirationDate2"))) {
				queryString.append(" and c.expirationDate <= to_date(:expirationDate2,'yyyy-mm-dd')");
			}
			if (queryMap.get("contractTypeIdList") != null && !"".equals(queryMap.get("contractTypeIdList"))) {
				queryString.append(" and c.contractType.typeId in (:contractTypeIdList)");
			}
			if (queryMap.get("wharfNameArray") != null && !"".equals(queryMap.get("wharfNameArray"))) {
				String[] wharf = (String[]) queryMap.get("wharfNameArray");
				queryString.append(" and (");
				int i = 1;
				for (String string : wharf) {
					queryString.append(" c.wharf like " + "'%" + string + "%'");
					if (i != wharf.length) {
						queryString.append(" or");
					}
					i++;
				}
				queryString.append(" )");
				queryMap.remove("wharfIdList");
				queryMap.remove("wharfId");
				queryMap.remove("wharfNameArray");
			}
			// if (queryMap.get("wharfIdList") != null
			// && !"".equals(queryMap.get("wharfIdList"))) {
			// queryString.append(" and c.wharf.wharfId in (:wharfIdList)");
			// }
		}
		queryString.append(this.changeOrder(page));
		List<Contract> list = contractDao.search(queryString.toString(), queryMap, page);
		pageEntity.setTotalRecord(contractDao.getPageEntity().getTotalRecord());
		return list;
	}

	public LinkedHashMap<String, String> getContractSelectMap(String id) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			List<Contract> list = contractDao.getContractSelectMap(id);
			for (Contract contract : list) {
				map.put(contract.getContractId().toString(),
						contract.getContractNo());
			}
		return map;
	}
	
	
	public Contract findById(Long id){
		Contract vo = contractDao.findById(id);
		if(vo != null)
			vo.getContractRateSet().size();
		return vo;
	}
/**
 * 
 * true唯一
 * 
 **/
	public boolean valiContractNo(String contractNO) {
		boolean bool = false;
		bool = contractDao.valiContractNo(contractNO);
		return bool;
	}
	
	private String changeOrder(PageEntity entity) {
		String str = " order by c.";
		if (entity != null && entity.getField() != null
				&& !entity.getField().equals("")) {
			if (entity.getField().equals("companySName"))
				str += "company.companySName ";
			else if (entity.getField().equals("contractType"))
				str += "contractType.typeId ";
			else if (entity.getField().equals("contractNo"))
				str += "contractNo ";
			else if (entity.getField().equals("effectiveDate"))
				str += "effectiveDate ";
			else if (entity.getField().equals("expirationDate"))
				str += "expirationDate ";
			else if (entity.getField().equals("wharfName"))
				str += "wharf ";
			str += entity.getOrder();
		} else {
			str += "company.companySName asc";
		}
		return str;
	}

	@Override
	@Transactional(readOnly = false,rollbackFor={Exception.class})
	public boolean delete(List<Contract> t) throws Exception {
		for(Contract cnt : t){
			Contract vo = contractDao.findById(cnt.getContractId());
			if(vo.getContractRateSet().size() > 0) 
				throw new Exception("合同编号为" + vo.getContractNo() + "的合同已经被合同汇率引用");
			contractDao.remove(vo);
		}
		//contractDao.remove(t);
		return true;
	}

	@Transactional(readOnly = false,rollbackFor={Exception.class})
	public void copy(Contract t) throws Exception{
		t.setContractId(null);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("contractNo", t.getContractNo());
		List<Contract> ls = contractDao.list(map, null, 0, 0);
		if(ls.size() > 0) throw new Exception("已经存在相同的合同编号");
		contractDao.save(t);
	}

	@Override
	@Transactional(readOnly = false)
	public boolean update(Contract t) throws Exception {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("contractNo", t.getContractNo());
		List<Contract> ls = contractDao.list(map, null, 0, 0);
		Contract vo = null;
		if(ls.size() > 0){ 
			vo = ls.get(0);
			if(!ls.get(0).getContractId().equals(t.getContractId()))
				throw new Exception("已经存在相同的合同编号");
		}else{
			vo = contractDao.findById(t.getContractId());
		}
		if(vo == null) 
			throw new Exception("修改的数据不存在，可能已经被删除");
		int commitNum = 0;
		for(ContractRate rate : vo.getContractRateSet()){
			if("Y".equalsIgnoreCase(rate.getRatestutas())) {
				commitNum ++;
				break;
			}
		}
		if(commitNum > 0){
			vo.setExpirationDate(t.getExpirationDate());
			vo.setRemarks(t.getRemarks());
			vo.setUpdatePerson(t.getUpdatePerson());
		}else{
			vo.setCompany(t.getCompany());
			vo.setContractNo(t.getContractNo());
			vo.setContractType(t.getContractType());
			vo.setEffectiveDate(t.getEffectiveDate());
			vo.setExpirationDate(t.getExpirationDate());
			vo.setWharf(t.getWharf());
			vo.setRemarks(t.getRemarks());
			vo.setUpdatePerson(t.getUpdatePerson());
		}
		return true;
	}

	public ContractRateDaoImpl getContractRateDao() {
		return contractRateDao;
	}

	@Resource(name = "contractRateDaoImpl")
	public void setContractRateDao(ContractRateDaoImpl contractRateDao) {
		this.contractRateDao = contractRateDao;
	}
}
